package com.example.service.impl;

import com.example.entity.singerAndGame.GSRelative;
import com.example.entity.singerAndGame.GameStatistics;
import com.example.mapper.GAndSMapper;
import com.example.mapper.VoteMapper;
import com.example.mapper.GameStatisticsMapper;
import com.example.service.GameStatisticsService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GameStatisticsServiceImpl implements GameStatisticsService {

    @Resource
    GameStatisticsMapper mapper;

    @Resource
    VoteMapper voteMapper;

    @Resource
    GAndSMapper gAndSMapper;

    @Override
    public List<GameStatistics> getGameStatisticsByGid(int gid) {
        return mapper.getGameStatisticsByGid(gid);
    }

    @Override
    public String addGameStatistics(int gid) {
        List<Integer> count = voteMapper.getVoteCountByGid(gid);
        int allCount = count.stream().reduce(0, Integer::sum);
        List<GSRelative> gsRelativeList = gAndSMapper.getGSRelativeByGid(gid);

        if (count.size() != gsRelativeList.size()) {
            return "比赛数据统计失败：票数和关联实体数量不匹配";
        }

        GameStatistics statistics = new GameStatistics();
        statistics.setGid(gid);

        for (int i = 0; i < count.size(); i++) {
            statistics.setSid(gsRelativeList.get(i).getSid());
            statistics.setCount(count.get(i));
            double score = gsRelativeList.get(i).getJudge_score() * 0.7 +
                    (statistics.getCount() / (double) allCount) * 100 * 0.3;
            statistics.setScore(score);

            if (mapper.addGameStatistics(statistics) < 0) {
                return "比赛数据统计失败";
            }
        }

        return null;
    }


    @Override
    public String deleteGameStatisticsByGid(int gid) {
        return mapper.deleteGameStatisticsByGid(gid) > 0 ? null : "比赛数据删除失败";
    }
}
